import 'dart:collection';

import 'package:share_fit/app/controllers/base/base_controller.dart';
import 'package:share_fit/app/tools/app_lang_const.dart';
import 'package:share_fit/app/tools/locale_tool.dart';
import 'package:share_fit/app/tools/log_utils.dart';
import 'package:share_fit/app/ute/uteped_const.dart';

import 'state.dart';

class LanguageLogic extends BaseController {
  final LanguageState state = LanguageState();
  static const methodSetLanguage = "setLanguage";
  static const methodQueryDeviceSupportLanguage = "queryDeviceSupportLanguage";

  @override
  String getRemotePath() {
    return UTEPedConst.pathCommon;
  }

  @override
  void initState() {
    state.followSysLang.value = read(UTEPedConst.keyLanguageFollowSystem, defaultValue: false, global: true);
    state.selectedLang.value = read(UTEPedConst.keyLanguage, defaultValue: 0, global: true);
    _queryLanguages();
  }

  @override
  void onRemoteEvent(event, method) {
    // TODO: implement onRemoteEvent
  }

  void setFollowSysLang(bool value) {
    state.followSysLang.value = value;
    // dsm_ 是前缀，为device settings more， 对应更多设置
    save(UTEPedConst.keyLanguageFollowSystem, state.followSysLang.value, global: true);
    if (value) {
      LocaleTool.inst.getSysLocale().then((value) {
        LocaleTool.updateLocale(value);
        state.selectedLang.value = 0;

        // 当跟随系统switch打开时，清除语言列表选中
        save(UTEPedConst.keyLanguage, 0, global: true);
        save(UTEPedConst.keyLanguageFollowSystem, true, global: true);
      });
    } else {
      var language = read(UTEPedConst.keyLanguage, defaultValue: -1, global: true);
      if (language > 0) {
        bRemoteReqAsync(methodSetLanguage, {UTEPedConst.keyLanguage: language});
      }
      else {
        for (var languageItem in state.languages) {
          var language = languageItem[UTEPedConst.keyLanguage];
          var languageCode = languageItem["code"];
          if (languageCode != LocaleTool.locale) {
            // LocaleTool.updateLocale(languageCode);
            showLoading();
            bRemoteReqAsync(methodSetLanguage, {UTEPedConst.keyLanguage: language}).then((success) => _onSetLanguage(success, language, languageItem));
            // 当跟随系统switch关闭时，保存switch状态到全局
            save(UTEPedConst.keyLanguageFollowSystem, false, global: true);
            break;
          }
        }
      }
    }
  }

  void _queryLanguages() {
    dRemoteReqAsync(methodQueryDeviceSupportLanguage, {}).then((value) {
      logger.d(value);
      Set langSet = SplayTreeSet.from(value);
      for (var lang in langSet) {
        Map? l = AppLangConst.getLanguage(lang);
        if (l != null) {
          state.languages.add(l);
        }
      }
      update(['language_list']);
    });
  }

  void onLanguageSelected(language, langMap) {
    if (language == null) {
      return;
    }
    setLanguage(language, langMap);

    // 当选中某个语言时，关闭跟随系统switch，并保存到全局
    state.followSysLang.value = false;
    save(UTEPedConst.keyLanguageFollowSystem, false, global: true);
  }

  void setLanguage(language, langMap) {
    if (state.selectedLang.value == language) {
      return;
    }
    showLoading();
    bRemoteReqAsync(methodSetLanguage, {UTEPedConst.keyLanguage: language}).then((success) => _onSetLanguage(success, language, langMap));
  }

  void _onSetLanguage(success, language, langMap) {
    cancelLoading();
    if (success) {
      state.selectedLang.value = language;
      save(UTEPedConst.keyLanguage, language, global: true);
      save(UTEPedConst.keyLanguageCode, langMap['code'], global: true);
      save(UTEPedConst.keyLanguageName, langMap['name'], global: true);
      LocaleTool.updateLocale(langMap['code']);
    }
  }
}
